##########################################################################################

library(dplyr)
library(data.table)
library(optparse)
library(ggplot2)
library("FactoMineR")
library("factoextra")

##########################################################################################
option_list <- list(
   make_option(c("--input_tmm_file"), type = "character"),
   make_option(c("--input_tpm_file"), type = "character"),
   make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
   input_tmm_file <- "~/20220915_gastric_multiple/rna_combine/analysis/images/DiffGene/CombineCounts.FilterLowExpression-MergeMutiSample.TMM.tsv"
   input_tpm_file <- "~/20220915_gastric_multiple/rna_combine/analysis/RSEM/CombineTpm.FilterLowExpression-MergeMutiSample.tsv"  
   out_path <- "~/20220915_gastric_multiple/rna_combine/analysis/images/DiffGene"

}

###########################################################################################
parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

input_tmm_file <- opt$input_tmm_file
input_tpm_file <- opt$input_tpm_file
out_path <- opt$out_path

#################################################
## 检查批次效应是否去干净
pca.plot = function(dat , col , out_file){

    df.pca <- PCA(t(dat), graph = FALSE)
    fviz_pca_ind(df.pca,
       geom.ind = "point",
       col.ind = col ,
       addEllipses = TRUE,
       legend.title = "Groups"
    )
}

## TMM
dat <- data.frame(fread(input_tmm_file))
disease <-  sapply(strsplit(colnames(dat)[-ncol(dat)] , "_") , "[" , 2)

## 现在的批次
out_file <- paste0( out_path , "/mRNA_TMM.pdf" )
pdf(out_file)
pca.plot( dat[,-ncol(dat)], factor(disease) , out_file)
dev.off()

## TPM
dat <- data.frame(fread(input_tpm_file))[,-1]
disease <-  sapply(strsplit(colnames(dat)[-1] , "_") , "[" , 2)

## 现在的批次
out_file <- paste0( out_path , "/mRNA_TPM.pdf" )
pdf(out_file)
pca.plot( dat[,-1], factor(disease) , out_file)
dev.off()

